package org.example.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.CurrentHolder;
import org.example.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //获取url
        String url = request.getRequestURI();
        //判断url是否包含login, 如果包含则放行
        if(url.contains("login")){
            log.info("登录请求, 放行");
            return true;
        }

        //如果不包含login,则获取token
        String jwt = request.getHeader("token");
        //判断token是否为空, 如果为空,则返回401
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空, 返回401");
            response.setStatus(401);
            return false;
        }
        // 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            log.info("token不为空, 解析token");
            Claims claims = JwtUtils.parseJWT(jwt);//解析token
            //解析登录Id
            Integer empId = Integer.valueOf(claims.get("id").toString());
            log.info("当前登录用户id为：{}",empId);
            CurrentHolder.set(empId);
        } catch (Exception e) {
            log.info("解析token失败，返回401");
            response.setStatus(401);
            return false;
        }

        //解析成功，放行
        log.info("token解析成功，放行");
        return true;
    }
}
